package com.xindaoapp.happypet.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.ui.PostDetailImgsActivity;
import com.xindaoapp.happypet.ui.ZanListActivity;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 帖子列表 适配器
 * 
 * @author Stone
 * 
 */

public class PostListAdapter extends XinDaoBaseAdapter<MainZuixinData.MainTiezi> {
    Map<Integer, ImageView> map = new HashMap<Integer, ImageView>();
    Map<Integer, Boolean> isZanMap = new HashMap<Integer, Boolean>();

    public PostListAdapter(Context context, List<MainZuixinData.MainTiezi> iniData, int pageSize,
            int res, int loadingRes) {
        super(context, iniData, pageSize, res, loadingRes);
    }

    // 需要重写
    @Override
    public void nextPage(int start, int size,
            final ILoadNextPageData<MainZuixinData.MainTiezi> iLoadNextPageData) {
        super.nextPage(start, size, iLoadNextPageData);

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent,
            final MainZuixinData.MainTiezi value) {
        ViewHolder holder = (ViewHolder) convertView.getTag();

        if (holder == null) {
            holder = new ViewHolder();
            holder.line = convertView.findViewById(R.id.line);
            holder.layout_imgs = (LinearLayout) convertView.findViewById(R.id.layout_imgs);
            holder.lay_zan = (RelativeLayout) convertView.findViewById(R.id.lay_zan);
            holder.layout_gozan = (RelativeLayout) convertView.findViewById(R.id.layout_gozan);
            holder.layout_gohuifu = (RelativeLayout) convertView.findViewById(R.id.layout_gohuifu);
            holder.iv_icon = (CircleImageView) convertView.findViewById(R.id.iv_icon);
            holder.iv_zan = (ImageView) convertView.findViewById(R.id.iv_zan);
            holder.iv_jing = (ImageView) convertView.findViewById(R.id.iv_jing);
            holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
            holder.tv_position = (TextView) convertView.findViewById(R.id.tv_position);
            holder.tv_zancount = (TextView) convertView.findViewById(R.id.tv_zancount);
            holder.tv_viewcount = (TextView) convertView.findViewById(R.id.tv_viewcount);
            holder.tv_huifucount = (TextView) convertView.findViewById(R.id.tv_huifucount);
            holder.tv_zanname1 = (TextView) convertView.findViewById(R.id.tv_zanname1);
            holder.tv_zanname2 = (TextView) convertView.findViewById(R.id.tv_zanname2);
            holder.tv_zanguo = (TextView) convertView.findViewById(R.id.tv_zanguo);
            convertView.setTag(holder);
        }

        map.put(position, holder.iv_zan);


        if (Integer.parseInt(value.recommend_add) > 0) {
            holder.tv_zancount.setText(value.recommend_add);
        } else {
            holder.tv_zancount.setText("赞");
        }
        // if (Integer.parseInt(value.replies) > 0) {
        holder.tv_huifucount.setText(value.replies);
        holder.tv_viewcount.setText(value.views);
        // } else {
        // holder.tv_huifucount.setText("回复");
        // }

        ImageLoader.getInstance().displayImage(value.userface, holder.iv_icon,
                BitmapUtil.getPersonLoading());

        holder.tv_name.setText(value.author);
        holder.tv_time.setText(CommonUtil.formatTimeForListCommon(value.updatetime));

        if (!value.subject.equals("")) {
            holder.tv_title.setVisibility(View.VISIBLE);
            holder.tv_title.setText(CommonUtil.convetToHtml(CommonUtil.parseEmoji(value.subject),
                    mContext));
        } else {
            holder.tv_title.setVisibility(View.GONE);
        }

        if (!value.message.equals("")) {
            holder.tv_content.setVisibility(View.VISIBLE);
            holder.tv_content.setText(CommonUtil.convetToHtml(CommonUtil.parseEmoji(value.message),
                    mContext));
        } else {
            holder.tv_content.setVisibility(View.GONE);
        }

        if (Integer.parseInt(value.digest) > 0) {
            holder.iv_jing.setVisibility(View.VISIBLE);
        } else {
            holder.iv_jing.setVisibility(View.GONE);
        }

        if (value.recommendmy.equals("1")) {
            isZanMap.put(position, true);
            holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_click);
        } else {
            isZanMap.put(position, false);
            holder.iv_zan.setImageResource(R.drawable.icon_hand_frs_normal);
        }

        if (value.forumname != null && value.forumname.length() != 0) {
            holder.tv_position.setText(value.forumname);
        }

        if (value.recommendarray.size() > 0) {
            holder.line.setVisibility(View.VISIBLE);
            holder.lay_zan.setVisibility(View.VISIBLE);
            if (value.recommendarray.size() >= 2) {
                holder.tv_zanname1.setText(value.recommendarray.get(0).username + "、");
                holder.tv_zanname2.setText(value.recommendarray.get(1).username);
                holder.tv_zanguo.setText("等" + value.recommendtotal + "人赞过");
            } else {
                holder.tv_zanname1.setText(value.recommendarray.get(0).username);
                holder.tv_zanname2.setText("");
                holder.tv_zanguo.setText("赞过");
            }
        } else {
            holder.line.setVisibility(View.GONE);
            holder.lay_zan.setVisibility(View.GONE);
        }


        // 视频或者图片
        if (holder.layout_imgs != null) {
            holder.layout_imgs.removeAllViews();
        }
        holder.layout_imgs.setVisibility(View.GONE);
        if (value.isvideo != null && value.isvideo.equals("1")) {
            holder.layout_imgs.setVisibility(View.VISIBLE);
            View sView = View.inflate(mContext, R.layout.image_pet_icon_shipinzuixin, null);
            ImageView iv = (ImageView) sView.findViewById(R.id.pet_icon);
            android.view.ViewGroup.LayoutParams lp1 = iv.getLayoutParams();
            TextView community_title = (TextView) sView.findViewById(R.id.community_title);
            lp1.width = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
            lp1.height = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
            iv.setScaleType(ScaleType.CENTER_CROP);
            iv.setLayoutParams(lp1);

            if (CommonParameter.isLoadImg) {
                ImageLoader.getInstance().displayImage(value.videocover, iv);
            } else {
                iv.setImageResource(R.drawable.picture_loading);
            }
            // community_title.setVisibility(View.VISIBLE);
            // community_title.setText(ParseMsgUtil.convetToHtml(CommonUtil.parseEmoji(value.subject),
            // mContext));
            LayoutParams lp =
                    new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            sView.setLayoutParams(lp);
            holder.layout_imgs.addView(sView);
        } else if (value.isvideo == null || value.isvideo.equals("0")) {
            if (value.pics.size() > 0) {
                holder.layout_imgs.setVisibility(View.VISIBLE);
            }
            for (int i = 0; i < value.pics.size(); i++) {
                final int j = i;
                LinearLayout view1 =
                        (LinearLayout) View.inflate(mContext, R.layout.image_pet_icon_zuixin, null);
                LinearLayout layout_count =
                        (LinearLayout) view1.findViewById(R.id.layout_for_count);
                TextView tv_mycount = (TextView) view1.findViewById(R.id.tv_mycount);

                ImageView iv1 = (ImageView) view1.findViewById(R.id.pet_icon);
                android.view.ViewGroup.LayoutParams lp2 = iv1.getLayoutParams();

                lp2.width = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                lp2.height = (CommonParameter.sScreenWidth - CommonUtil.dp2px(mContext, 46.2f)) / 3;
                iv1.setScaleType(ScaleType.CENTER_CROP);
                iv1.setLayoutParams(lp2);
                if (CommonParameter.isLoadImg) {
                    ImageLoader.getInstance().displayImage(value.pics.get(i).url, iv1);
                } else {
                    iv1.setImageResource(R.drawable.picture_loading);
                }
                LayoutParams lp3 =
                        new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                if (i == 2 && Integer.parseInt(value.picnum) > 3) {
                    tv_mycount.setText("共" + value.picnum + "张");
                    layout_count.setVisibility(View.VISIBLE);
                }


                if (i > 0) {
                    lp3.leftMargin = CommonUtil.dip2px(mContext, 5);
                }

                view1.setLayoutParams(lp3);

                view1.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO 到图片集
                        skipToImgs(value.pics.get(j).aid, value.tid);
                    }


                });
                holder.layout_imgs.addView(view1);

            }
        }



        final OnClickListener itemClickListener = new OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                switch (view.getId()) {
                    case R.id.iv_icon:
                    case R.id.tv_name:
                    case R.id.tv_time:
                        // 进入他人中心
                        goOthersCenter(value.authorid, value.author, value.userface);
                        break;

                    case R.id.tv_zanname1:
                        // 进入该人中心
                        if (value.recommendarray != null && value.recommendarray.size() > 0) {
                            goOthersCenter(value.recommendarray.get(0).recommenduid,
                                    value.recommendarray.get(0).username,
                                    value.recommendarray.get(0).userface);
                        }
                        break;
                    case R.id.tv_zanname2:
                        // 进入该人中心
                        if (value.recommendarray != null && value.recommendarray.size() > 1) {
                            goOthersCenter(value.recommendarray.get(1).recommenduid,
                                    value.recommendarray.get(1).username,
                                    value.recommendarray.get(1).userface);
                        }
                        break;
                    case R.id.layout_gohuifu:
                        // 回复
                        // 进入展示图片切换
                        Toast.makeText(mContext, "进入回复!", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.layout_gozan:
                    case R.id.tv_zancount:
                    case R.id.iv_zan:
                        // 点赞
                        goZan(position, value);

                        break;
                    case R.id.lay_zan:
                        // 进入点赞列表
                        Intent i = new Intent(mContext, ZanListActivity.class);
                        i.putExtra("title", value.subject);
                        i.putExtra("tid", value.tid);
                        i.putExtra("totalzan", Integer.parseInt(value.recommend_add));
                        mContext.startActivity(i);
                        break;

                    default:
                        break;
                }

            }

            private void goOthersCenter(String uid, String name, String userface) {
                // TODO Auto-generated method stub
                // 进入他人中心
                Intent intent =
                        new Intent(mContext, com.xindaoapp.happypet.activity.MainActivity.class);
                intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                        UserInfoFragment.class.getCanonicalName());
                Bundle bundle = new Bundle();
                bundle.putString(Constants.KEY_UID, uid);
                bundle.putString(Constants.KEY_USERNAME, name);
                bundle.putString(Constants.KEY_USERFACE, userface);
                intent.putExtra(Constants.KEY_BUNDLE, bundle);
                mContext.startActivity(intent);
            }
        };

        OnClickListener videoClickListener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 处理视频点击
                Toast.makeText(mContext, "进入视频 !", Toast.LENGTH_SHORT).show();
            }
        };
        // 进入赞列表
        holder.lay_zan.setOnClickListener(itemClickListener);
        // 进入个人中心
        holder.iv_icon.setOnClickListener(itemClickListener);
        holder.tv_name.setOnClickListener(itemClickListener);
        holder.tv_time.setOnClickListener(itemClickListener);

        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =
                        new Intent(mContext, com.xindaoapp.happypet.ui.PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, value.tid);
                mContext.startActivity(intent);
            }
        });

        return convertView;
    }

    protected void skipToImgs(String aid, String tid) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(mContext, PostDetailImgsActivity.class);
        intent.putExtra(Constants.PARAM_PHOTO_POSITION, aid);
        intent.putExtra(Constants.KEY_POST_TID, tid);
        mContext.startActivity(intent);
    }

    private void goZan(final int position, final MainZuixinData.MainTiezi value) {

        // TODO Auto-generated method stub
        if (UserState.isLogged((Activity) mContext)) {
            if (isZanMap.get(position)) {
                Toast.makeText(mContext, "已赞过 !", Toast.LENGTH_SHORT).show();
            } else {
                if (CommonUtil.checkNetState(mContext)) {

                    map.get(position).setImageResource(R.drawable.icon_hand_frs_click);


                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                        final ObjectAnimator oa =
                                ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)), "width",

                                CommonUtil.dip2px(mContext, 0), CommonUtil.dip2px(mContext, 40));
                        final ObjectAnimator ob =
                                ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)), "height",

                                CommonUtil.dip2px(mContext, 0), CommonUtil.dip2px(mContext, 40));
                        oa.setInterpolator(new AccelerateDecelerateInterpolator());
                        ob.setInterpolator(new AccelerateDecelerateInterpolator());
                        oa.setDuration(250);
                        ob.setDuration(250);


                        final AnimatorSet set = new AnimatorSet();
                        set.play(oa).with(ob);

                        set.addListener(new AnimatorListener() {

                            @Override
                            public void onAnimationStart(Animator arg0) {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onAnimationRepeat(Animator arg0) {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onAnimationEnd(Animator arg0) {
                                // TODO Auto-generated method stub


                                ObjectAnimator oa2 =
                                        ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                                "width", CommonUtil.dip2px(mContext, 40),
                                                CommonUtil.dip2px(mContext, 25));
                                ObjectAnimator ob2 =
                                        ObjectAnimator.ofInt(new ViewWrapper2(map.get(position)),
                                                "height", CommonUtil.dip2px(mContext, 40),
                                                CommonUtil.dip2px(mContext, 25));
                                oa2.setInterpolator(new AccelerateDecelerateInterpolator());
                                ob2.setInterpolator(new AccelerateDecelerateInterpolator());
                                oa2.setDuration(250);
                                ob2.setDuration(250);

                                AnimatorSet set2 = new AnimatorSet();
                                set2.play(oa2).with(ob2);
                                set2.start();

                            }

                            @Override
                            public void onAnimationCancel(Animator arg0) {
                                // TODO Auto-generated method stub

                            }
                        });

                        set.start();
                    }


                    RequestParams params = new RequestParams();
                    params.put("tid", value.tid);
                    params.put("uid", UserState.getUserUid());
                    XDHttpClient.get(xdConfig.PRAISEPOST, params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, String content) {

                            try {
                                if (new JSONObject(content).getInt("result") == 0) {

                                    MainZuixinData.MainTiezi.RecommendPerson info =
                                            new MainZuixinData().new MainTiezi().new RecommendPerson();
                                    info.username = UserState.getUser().username;
                                    info.recommenduid = UserState.getUserUid();
                                    value.recommendarray.add(0, info);
                                    value.recommendmy = "1";
                                    value.recommend_add =
                                            String.valueOf(Integer.parseInt(value.recommend_add) + 1);
                                    isZanMap.put(position, true);
                                    Toast.makeText(mContext, "点赞成功", Toast.LENGTH_SHORT).show();
                                    notifyDataSetChanged();
                                } else {
                                    map.get(position).setImageResource(
                                            R.drawable.icon_hand_frs_normal);
                                    Toast.makeText(mContext, "点赞失败", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Throwable arg0, String arg1) {
                            super.onFailure(arg0, arg1);
                            map.get(position).setImageResource(R.drawable.icon_hand_frs_normal);
                            Toast.makeText(mContext, R.string.get_error_data, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                } else {
                    Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }
            }
        }

    }



    private class ViewWrapper2 {
        private final View mTarget;

        public ViewWrapper2(View target) {
            mTarget = target;
        }

        public int getWidth() {
            return mTarget.getLayoutParams().width;
        }

        public void setWidth(int width) {
            mTarget.getLayoutParams().width = width;
            mTarget.requestLayout();
        }

        public int getHeight() {
            return mTarget.getLayoutParams().height;
        }

        public void setHeight(int height) {
            mTarget.getLayoutParams().height = height;
            mTarget.requestLayout();
        }
    }


    class ViewHolder {
        View line;
        LinearLayout layout_imgs;
        RelativeLayout lay_zan, layout_gozan, layout_gohuifu;
        CircleImageView iv_icon;
        ImageView iv_zan, iv_huifu, iv_jing;
        TextView tv_name, tv_time, tv_title, tv_content, tv_position, tv_zancount, tv_huifucount,
                tv_zanname1, tv_viewcount, tv_zanname2, tv_zanguo;
    }
}
